package com.example.hasee.zhcd.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.example.hasee.zhcd.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class NewDateTimePickDialogUtil implements OnDateChangedListener,
        OnTimeChangedListener {
    private DatePicker datePicker;
    private TimePicker timePicker;
    private AlertDialog ad;
    private String dateTime;
    private String initDateTime;
    private Activity activity;

    public NewDateTimePickDialogUtil(Activity activity, String initDateTime) {
        this.activity = activity;
        this.initDateTime = initDateTime;

    }

    public void init(DatePicker datePicker, TimePicker timePicker) {
        Calendar calendar = Calendar.getInstance();
        if (!(null == initDateTime || "".equals(initDateTime))) {
            calendar = this.getCalendarByInintData(initDateTime);
        } else {
            initDateTime = calendar.get(Calendar.YEAR) + "-"
                    + calendar.get(Calendar.MONTH) + "-"
                    + calendar.get(Calendar.DAY_OF_MONTH) + " " +
                    calendar.get(Calendar.HOUR_OF_DAY) + ":"
                    + calendar.get(Calendar.MINUTE);
        }
        datePicker.init(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), this);
        timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
    }


    public AlertDialog dateTimePicKDialog(final EditText inputDate) {
        LinearLayout dateTimeLayout = (LinearLayout) activity
                .getLayoutInflater().inflate(R.layout.new_common_datetime, null);
        datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.datepicker);
        timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.timepicker);
        init(datePicker, timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
        setNumberPickerTextSize(timePicker);

        ad = new AlertDialog.Builder(activity)
                .setTitle(initDateTime)
                .setView(dateTimeLayout)
                .setPositiveButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        datePicker.clearFocus();
                        onDateChanged(null, 0, 0, 0);
                        if (inputDate.getText().toString().equals("")) {
                            inputDate.setText("");
                        }

                    }
                })
                .setNegativeButton(activity.getString(R.string.sure), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        datePicker.clearFocus();
                        onDateChanged(null, 0, 0, 0);
                        inputDate.setText(dateTime);

                    }
                }).show();

        return ad;
    }

    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

//        dateTime = sdf.format(calendar.getTime());
//        if (Integer.parseInt(sdf.format(calendar.getTime()).substring(15, sdf.format(calendar.getTime()).length())) % 10 >= 5) {
//            dateTime = sdf.format(calendar.getTime()).substring(0, 15) + "5";
//        } else {
//            dateTime = sdf.format(calendar.getTime()).substring(0, 15) + "0";
//        }
        int fa_minite = Integer.parseInt(sdf.format(calendar.getTime()).substring(14, sdf.format(calendar.getTime()).length()));
        int tr_minite = fa_minite * 5;
        String en_minite = tr_minite + "";
        if (en_minite.length() == 1) {
            en_minite = "0" + en_minite;
        }
        dateTime = sdf.format(calendar.getTime()).substring(0, 14) + en_minite;
        ad.setTitle(dateTime);
        ad.setTitle(dateTime);
    }

    public void onDateChanged(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

//        dateTime = sdf.format(calendar.getTime());
//        if (Integer.parseInt(sdf.format(calendar.getTime()).substring(15, sdf.format(calendar.getTime()).length())) % 10 >= 5) {
//            dateTime = sdf.format(calendar.getTime()).substring(0, 15) + "5";
//        } else {
//            dateTime = sdf.format(calendar.getTime()).substring(0, 15) + "0";
//        }
        int fa_minite = Integer.parseInt(sdf.format(calendar.getTime()).substring(14, sdf.format(calendar.getTime()).length()));
        int tr_minite = fa_minite * 5;
        String en_minite = tr_minite + "";
        if (en_minite.length() == 1) {
            en_minite = "0" + en_minite;
        }
        dateTime = sdf.format(calendar.getTime()).substring(0, 14) + en_minite;
        ad.setTitle(dateTime);
    }

    private Calendar getCalendarByInintData(String initDateTime) {
        Calendar calendar = Calendar.getInstance();
        int currentYear = Integer.parseInt(initDateTime.substring(0, 4));
        int currentMonth = Integer.parseInt(initDateTime.substring(5, 7)) - 1;
        int currentDay = Integer.parseInt(initDateTime.substring(8, 10));
        /*
        * 这是改的
        * */
        int currentHour = Integer.parseInt(initDateTime.substring(11,
                13));
        int currentMinite = Integer.parseInt(initDateTime.substring(14,
                initDateTime.length())) / 5;
//        int currentMinite;
//        if (Integer.parseInt(initDateTime.substring(14,
//                initDateTime.length())) % 10 >= 5) {
//            currentMinite = Integer.parseInt(initDateTime.substring(14,
//                    initDateTime.length() - 1) + "5");
//        } else {
//            currentMinite = Integer.parseInt(initDateTime.substring(14,
//                    initDateTime.length() - 1) + "0");
//        }
        calendar.set(currentYear, currentMonth, currentDay, currentHour, currentMinite);

        return calendar;
    }

    //设置时间间隔
    String[] minuts = new String[]{"00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"};

    /**
     * 得到timePicker里面的android.widget.NumberPicker组件 （有两个android.widget.NumberPicker组件--hour，minute）
     *
     * @param viewGroup
     * @return
     */
    private List<NumberPicker> findNumberPicker(ViewGroup viewGroup) {
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;

        if (null != viewGroup) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                child = viewGroup.getChildAt(i);
                if (child instanceof NumberPicker) {
                    npList.add((NumberPicker) child);
                } else if (child instanceof LinearLayout) {
                    List<NumberPicker> result = findNumberPicker((ViewGroup) child);
                    if (result.size() > 0) {
                        return result;
                    }
                }
            }
        }

        return npList;
    }

    /**
     * 查找timePicker里面的android.widget.NumberPicker组件 ，并对其进行时间间隔设置
     *
     * @param viewGroup TimePicker timePicker
     */
    private void setNumberPickerTextSize(ViewGroup viewGroup) {
        List<NumberPicker> npList = findNumberPicker(viewGroup);
        if (null != npList) {
            for (NumberPicker mMinuteSpinner : npList) {
//              System.out.println("mMinuteSpinner.toString()="+mMinuteSpinner.toString());
                if (mMinuteSpinner.toString().contains("id/minute")) {//对分钟进行间隔设置

                    mMinuteSpinner.setMinValue(0);
                    mMinuteSpinner.setMaxValue(minuts.length - 1);
                    mMinuteSpinner.setDisplayedValues(minuts);  //这里的minuts是一个String数组，就是要显示的分钟值
                }
                //对小时进行间隔设置 使用 if(mMinuteSpinner.toString().contains("id/hour")){}即可
            }
        }
    }
}
